import requests  
import Py4Js    
import json
import time
import sys
import os
import random
import requests

def py():
    url = 'http://fanyi.baidu.com/v2transapi/'
    while True:
        print('感谢百度翻译，禁止用于商业用途')
        print('----------------------------')
        content=input("中译英请输入1，英译中请输入2，退出请输入Q\n")
        if content in['Q']:
            break;
        elif content in['2']:
            content=input("请输入翻译内容\n")
            data={
               ' from':'en','to':'zh','query':content  , 
               'transtype':'translang',
               'simple_means_flag':'3',
            }
        elif content in['1']:
            content=input("请输入翻译内容\n")
            data={
               ' from':'zh','to':'en','query':content  , 
               'transtype':'translang',
               'simple_means_flag':'3',
            }
        
        headers ={'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36 SE 2.X MetaSr 1.0'}
        response = requests.post(url,data,headers=headers)
        head = response.headers
 
            #text = response.text
            #text = json.loads(text)
            #res = text['trans_result']['data'][0]['dst']
            #print(res)
            #print(head['Content-Type'])
        print(response.json())   
        #print(response.json()['trans_result']['data'][0]['dst'])


def translate(tk,content):   
    if len(content) > 4891:    
        print("翻译的长度超过限制！！！" + str(len(content)))    
        return  
 
    param = {'tk': tk, 'q': content}
 
    result = requests.get("""http://translate.google.cn/translate_a/single?client=t&sl=en
        &tl=zh-CN&hl=zh-CN&dt=at&dt=bd&dt=ex&dt=ld&dt=md&dt=qca&dt=rw&dt=rm&dt=ss
        &dt=t&ie=UTF-8&oe=UTF-8&clearbtn=1&otf=1&pc=1&srcrom=0&ssel=0&tsel=0&kc=2""", params=param)
 
    #返回的结果为Json，解析为一个嵌套列表
    for text in result.json():
        #print(text)
        return text
     
#from googletrans import Translator

    
def main():    

    #py()

    # js = Py4Js.Py4Js()    
         
    # content = """Beautiful is better than ugly.
        # Explicit is better than implicit.
        # Simple is better than complex.
        # Complex is better than complicated.
        # Flat is better than nested.
        # Sparse is better than dense.
        # Readability counts.
        # Special cases aren't special enough to break the rules.
        # Although practicality beats purity.
        # Errors should never pass silently.
        # Unless explicitly silenced.
        # In the face of ambiguity, refuse the temptation to guess.
        # There should be one-- and preferably only one --obvious way to do it.
        # Although that way may not be obvious at first unless you're Dutch.
        # Now is better than never.
        # Although never is often better than *right* now.
        # If the implementation is hard to explain, it's a bad idea.
        # If the implementation is easy to explain, it may be a good idea.
        # Namespaces are one honking great idea -- let's do more of those!"""
 
    # tk = js.getTk(content)    
    # translate(tk,content)    
    
    fileName = "./cn/captions_val2014.json"
    checkFile(fileName)
    fileName = "./cn/captions_train2014.json"
    checkFile(fileName)
    
    # translated = 0
    # with open(fileName,'r',encoding = 'utf-8') as load_f:
        # load_dict = json.load(load_f)
        # #key:info, images, licenses,annotations
        # annotations = load_dict['annotations']
        # print(type(annotations))
        # content_100 = ""
        # content_dict = {}
        # content_i = 0
        # splitWord = '%%%'
        # contentBatch = 50
        # clsTimer = 0
        # #for i in range(2): 
        # for i in range(len(annotations)):
            # #pass
            # #print(annotations[i])
            
            # content = annotations[i]['caption']
            
            # if 'translated' not in annotations[i]:
                
                
            
                # content_dict[content_i] = i
                # content_100 = content_100 + content + splitWord
                
                # content_i = content_i+1
                
                # if content_i == contentBatch :
                    # print(content_100)
                    # print(content_dict)
                    # js = Py4Js.Py4Js()
                    # tk = js.getTk(content)  
                    # trans_100 = translate(tk,content_100)[0][0]
                    # transArray = trans_100.split(splitWord)
                    # print(len(transArray))
                    # for i in range(len(transArray)-1):
                        # print(str(content_dict[i]) + '---' + str(annotations[content_dict[i]]['caption']))
                        # annotations[content_dict[i]]['caption'] = trans_100[i]
                        # annotations[content_dict[i]]['translated'] = '1'
                        # print(trans_100[i])
                        # print("############################################################################")
                    
                    # content_100 = ""
                    # content_dict.clear()
                    # content_i = 0
                    
                    # time.sleep(1+random.randint(2,5))
                    
                    # clsTimer = clsTimer + 1
                    # if clsTimer == 10:
                        # os.system("cls")
                        # clsTimer = 0
                        
                    # load_dict['annotations'] = annotations
                    # print('replace annotations done!')
                    # print('start write cn json.')
                    # with open(fileName,"w", encoding = 'utf-8') as f:
                        # json.dump(load_dict,f,ensure_ascii = False)
                        # print('write cn json done!')    
                 
                   
                # # translator = Translator()
                # # translator.translate('안녕하세요.')
                # # cn = translator.translate(content, dest='zh-CN')
                # '''
                # js = Py4Js.Py4Js()
                # tk = js.getTk(content)  
                # cn = translate(tk,content)[0][0]
                # annotations[i]['caption'] = cn
                # annotations[i]['translated'] = '1'
                # print(cn)
                # print(str(i) + '/' + str(len(annotations)))
                # time.sleep(1+random.randint(2,5))
            
                # if i%10 == 0:
                    # load_dict['annotations'] = annotations
                    # print('replace annotations done!')
                    # print('start write cn json.')
                    # with open(fileName,"w", encoding = 'utf-8') as f:
                        # json.dump(load_dict,f,ensure_ascii = False)
                        # print('write cn json done!')
                # '''
                
            # else:
                # translated = translated + 1
                # print(content + ' : translated.')\
                
        # print(str(translated) + " is translated. total is" + str(len(annotations)) + ', percent is ' + str(100 * translated/len(annotations)) + "%")
        
        # load_dict['annotations'] = annotations
        # print('replace annotations done!')
        # print('start write cn json.')
        # with open(fileName,"w", encoding = 'utf-8') as f:
            # json.dump(load_dict,f,ensure_ascii = False)
            # print('write cn json done!')
        
    

def checkFile(fileName):
    translated = 0
    with open(fileName,'r',encoding = 'utf-8') as load_f:
        load_dict = json.load(load_f)
        #key:info, images, licenses,annotations
        annotations = load_dict['annotations']
        print(type(annotations))
        content_100 = ""
        content_dict = {}
        content_i = 0
        splitWord = '\n\n\n'
        contentBatch = 50
        clsTimer = 0
        #for i in range(2): 
        for i in range(len(annotations)):
            #pass
            #print(annotations[i])
            
            content = annotations[i]['caption']
            
            if 'translated' not in annotations[i]:
                
                '''
            
                content_dict[content_i] = i
                content_100 = content_100 + content + splitWord
                
                content_i = content_i+1
                
                if content_i == contentBatch or i==(len(annotations)-1):
                    print(content_100)
                    print(content_dict)
                    js = Py4Js.Py4Js()
                    tk = js.getTk(content_100) 
                    trans_j = translate(tk,content_100)
                    #print(trans_j)	
                    trans_concat = ""	
                    #print(len(trans_j))						
                    for j in range(len(trans_j)-1):
                        print(trans_j[j])				
                        trans_concat = trans_concat + trans_j[j][0]
                    trans_100 = trans_concat
                    #print(trans_100)
                    transArray = trans_100.split(splitWord)
                    #print(transArray)
                    print(len(transArray))
                    for i in range(len(transArray)-1):
                        if i in content_dict:
                            print(str(content_dict[i]) + '---' + str(annotations[content_dict[i]]['caption']))
                            annotations[content_dict[i]]['caption'] = transArray[i]
                            annotations[content_dict[i]]['translated'] = '1'
                            print(transArray[i])
                            print("############################################################################")
                    
                    content_100 = ""
                    content_dict.clear()
                    content_i = 0
                    
                    time.sleep(1+random.randint(5,10))
                    
                    clsTimer = clsTimer + 1
                    if clsTimer == 5:
                        os.system("cls")
                        clsTimer = 0
                        
                    load_dict['annotations'] = annotations
                    print('replace annotations done!')
                    print('start write cn json.')
                    with open(fileName,"w", encoding = 'utf-8') as f:
                        json.dump(load_dict,f,ensure_ascii = False)
                        print('write cn json done!')    
                 
                  
                pass
                '''
            else:
                translated = translated + 1
                print(content + ' : translated.')\
                
        print(str(translated) + " is translated. total is" + str(len(annotations)) + ', percent is ' + str(100 * translated/len(annotations)) + "%")
        
        load_dict['annotations'] = annotations
        print('replace annotations done!')
        print('start write cn json.')
        with open(fileName,"w", encoding = 'utf-8') as f:
            json.dump(load_dict,f,ensure_ascii = False)
            print('write cn json done!')
    
            
        
if __name__ == "__main__":    
    main()